package com.bootdo.timing.controller;

import java.math.BigDecimal;
import java.security.Key;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.huobi.api.ApiClient;
import com.bootdo.common.huobi.response.Trade;
import com.bootdo.common.huobi.response.TradeResponse;
import com.bootdo.common.utils.*;
import com.bootdo.timing.dto.CountDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javafx.beans.binding.ObjectBinding;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SimpleTrigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.timing.domain.OrderDO;
import com.bootdo.timing.service.OrderService;

/**
 * 
 * 
 * @author caisj
 * @email 1992lcg@163.com
 * @date 2020-01-05 22:43:00
 */
 
@Controller
@RequestMapping("/timing/order")
public class OrderController {

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private OrderService orderService;
	
	@GetMapping()
	@RequiresPermissions("timing:order:order")
	String Order(){
	    return "timing/order/order";
	}



	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("timing:order:order")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		if ( 1==2 ){
			List<OrderDO> orderList = orderService.list(query);
			int total = orderService.count(query);
			PageUtils pageUtils = new PageUtils(orderList, total);
		}
		List<OrderDO> orderlist =new ArrayList<>();
		OrderDO orderDO = new OrderDO() ;
		orderDO.setBuyNum(new BigDecimal(2));
		orderDO.setFilled_fees(new BigDecimal(0.0001));
		orderDO.setTrade_id("1234567");
		orderDO.setBuyAmount(new BigDecimal(23));
		orderDO.setTradeOrder("123456");
		orderDO.setBuyPrice(new BigDecimal(0.01));
		orderDO.setScale(20);
		orderlist.add(orderDO);
		PageUtils pageUtils = new PageUtils(orderlist, 1);
		return pageUtils;
	}


	static final String API_KEY = "vf25treb80-b8eac013-31edf2a8-b52ef";
	static final String API_SECRET = "2fc7f904-ba416284-19d89a78-26aef";


	@ResponseBody
	@GetMapping("/getCount")
	public PageUtils getCount(@RequestParam Map<String, Object> params)  {
		try {
			// 火币接口查询每个币的价格  ，计算总价值 ，2，获取每个币种的价格 ， 分组  select type ,  sum(price) from order

			List<Map<String,Object >> typeList  = orderService.getGroupPriceByType();
			ApiClient client = new ApiClient(API_KEY, API_SECRET);
			List<CountDto> counts = new ArrayList<CountDto>();
			for (int i = 0 ; typeList.size() > i ; i++){
				String BuyMarktTotalPrice = "0";
				Map<String,Object > typeMap = typeList.get(i);
				CountDto countDto = new CountDto() ;
				String type = typeMap.get("currencyType")+"";
				String buyAmount = typeMap.get("buyAmount")+"";
				String buyNum = String.valueOf(typeMap.get("buyNum"));
				//获取币种的当前价格
				TradeResponse trade = client.trade(type);
				// 放入缓存中

				if (trade !=null && "ok".equals(trade.getStatus())) {
					JSONObject jsonObject = JSON.parseObject(trade.getTick().getData().toString()) ;
					String price = jsonObject.getString("price");  // 币的价格
					String  BuyMarktPrice = CalculationUtil.multiply(price,buyNum,4); // 市场价值 购买数*市场价
					BuyMarktTotalPrice = CalculationUtil.add(BuyMarktTotalPrice,BuyMarktPrice,4); //
//					countDto.setCurrencyType(type); // 币种
//					countDto.setBuyTotalNum(buyNum); // 购买总数量
//					countDto.setBuyTotalPrice(buyAmount); // 购买总价格
//					countDto.setMarktSinglePrice(price); // 市场单价
//					countDto.setMarktTotalPrice(BuyMarktTotalPrice); // 市场总价格
//					String proSalce = CalculationUtil.divide(CalculationUtil.subtract(BuyMarktTotalPrice,buyAmount ,2),buyAmount,2);
//					countDto.setProfitSacle(proSalce);
					counts.add(countDto);
				}

			}

			PageUtils pageUtils = new PageUtils(counts, counts.size());
			return pageUtils;
		}
		catch (Exception e ){
			e.printStackTrace();
		}
		return new PageUtils(new ArrayList<>() , 0);
	}






	@GetMapping("/add")
	@RequiresPermissions("timing:order:add")
	String add(){
	    return "timing/order/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("timing:order:edit")
	String edit(@PathVariable("id") Integer id,Model model){
		OrderDO order = orderService.get(id);
		model.addAttribute("order", order);
	    return "timing/order/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("timing:order:add")
	public R save( OrderDO order){
		if(orderService.save(order)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("timing:order:edit")
	public R update( OrderDO order){
		orderService.update(order);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("timing:order:remove")
	public R remove( Integer id){
		if(orderService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("timing:order:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids){
		orderService.batchRemove(ids);
		return R.ok();
	}
	
}
